package com.luocc.ccdemo.utils

import android.util.Log
import okhttp3.*
import java.net.URL
import java.util.concurrent.TimeUnit

/**
 * 用起来感觉没啥区别
 */
object OkHttpUtil {
    private var client: OkHttpClient? = null

    private const val TAG = "LC_OkHttpUtil"

    fun init(interceptors: List<Interceptor>) {
        if (client == null) {
            val builder = OkHttpClient().newBuilder()
                .readTimeout(6, TimeUnit.SECONDS)
                .connectTimeout(6, TimeUnit.SECONDS)
                .writeTimeout(6, TimeUnit.SECONDS)
            interceptors.forEach {
                builder.addInterceptor(it)
            }
            client = builder.build()
        }
    }

    /**
     * @param url 要访问的路径
     * @param map 要携带的body
     */
    fun post(url: URL, map: HashMap<String, String>): Response {
        if (client == null) throw RuntimeException("OkHttp未初始化")
        val builder = FormBody.Builder()
        map.entries.forEach {
            builder.add(it.key, it.value)
        }
        builder.build()
        // method: "method $method must have a request body."
        val request = Request.Builder().url(url).post(builder.build()).build()
        return client!!.newCall(request).execute()
    }

    /**
     * get不能有body，post必须有
     */
    fun get(url: URL): Response {
        Log.d(TAG, "get: ")
        Log.d(TAG, "get: ${Throwable().message}")
        if (client == null) throw RuntimeException("OkHttp未初始化")
        // "method $method must not have a request body."
        val request = Request.Builder().url(url).get().build()
        return client!!.newCall(request).execute()
    }
}